/**
 * @(#) OverView.as
 *
 * @date		2009. 04. 20.
 * @version		1.0
 * @author		Jo, ChangHun
 * @description	연말정산 메인 view - Mediator
 * 				연말정산 - 탭6 특별공제 보험료 팝업 Presentation Logic을 관리 
 */
package com.skt.common_hr.yearadjustment.view
{
	import com.skt.common_hr.common.PsHrAlert;
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.yearadjustment.YearAdjustmentFacade;
	import com.skt.common_hr.yearadjustment.events.DonationItemEvent;
	import com.skt.common_hr.yearadjustment.model.BizNumValidProxy;
	import com.skt.common_hr.yearadjustment.model.DonaInhabiComboProxy;
	import com.skt.common_hr.yearadjustment.model.DonationProxy;
	import com.skt.common_hr.yearadjustment.view.components.popDonation;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;
	
	public class popDonationMediator extends Mediator
	{
		public static const NAME:String = "popDonationMediator"; 
		public var v_year:String = "";
		[Bindable] public var v_enable:Boolean = true;
		
		//추가, 수정 구분
		private var bAdd:Boolean = true;	//추가 모드
		//수정시 선택된 아이템 인덱스
		private var itemIdx:int = -1;
		
		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function popDonationMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
            view.callLater(initView);
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		public function initView():void
 		{
 			view.addEventListener(popDonation.CleanData, onCleanData);
 			view.addEventListener(popDonation.OkInput, onOkInput);
 			view.addEventListener(popDonation.CancelInput, onCancelInput);
 			view.addEventListener(popDonation.AddItem, onAddItem);
 			view.addEventListener(DonationItemEvent.DONATION_ITEM_MODIFY, onModifyItem);
 			view.addEventListener(DonationItemEvent.DONATION_ITEM_DEL, onDelItem);
 			view._isEnable = v_enable;
 			
 			gubunComboSelect();
 			comboJumin();
 			//donationListSelect();
 		}
 		

//shgoo 2010.01.11 		
 		//사업자  번호 유효성 체크
 		private function loadBizNumValid():void {
 			var proxy:BizNumValidProxy = facade.retrieveProxy(BizNumValidProxy.NAME) as BizNumValidProxy;
 			//proxy.load(view.D_COMCD.text);
 		}
///////////////////
 		
 		//주민등록번호 콤보
 		private function comboJumin():void{
 			var proxy:DonaInhabiComboProxy = facade.retrieveProxy(DonaInhabiComboProxy.NAME) as DonaInhabiComboProxy;
 			proxy.comboload(Variables.yearPernr, v_year);
 		}
 		
 		private function onCleanData(event:Event):void{
 			view.mainDg.selectedIndex = -1;
 			cleanData();	
 		}
 		
 		//지급처 구분 콤보박스 로드
 		private function gubunComboSelect():void{
 			var proxy:DonationProxy = facade.retrieveProxy(DonationProxy.NAME) as DonationProxy;
 			proxy.comboload();
 		}
 		
 		private function donationListSelect():void{
 			var proxy:DonationProxy = facade.retrieveProxy(DonationProxy.NAME) as DonationProxy;
 			proxy.load(Variables.yearPernr, v_year);
 		}
 		
 		//저장
 		private function onOkInput(event:Event):void{
 			
 			var detailList:Array = new Array();
	 		for each(var rec:Object in view.DonationData)
	 		{
	 			detailList.push(rec);
	 		}
 			
 			var proxy:DonationProxy = facade.retrieveProxy(DonationProxy.NAME) as DonationProxy;
 			proxy.save(Variables.yearPernr, v_year, detailList);
 		}
 		
 		
 		//팝업 닫기
 		private function onCancelInput(event:Event):void
 		{
 			facade.removeMediator(popDonationMediator.NAME);
 			PopUpManager.removePopUp(view);
 		}
 		
//shgoo : 2009.06.01
		//입력항목  유효성 체크
		private function isInputValid():Boolean {
			/*
 			if(!isValidation(view.D_REGNO.selectedItem.CODE) && StringUtil.NVL(view.D_REGNO.selectedItem.CODE) != ""){
 				PsHrAlert.showMessage("주민등록번호 형식이 맞지 않습니다.");
 				return false;
 			}else if(StringUtil.NVL(view.D_YEASUB.selectedItem.CODE) == ""){
 				PsHrAlert.showMessage("지급처 구분을 선택해주세요.");
 				return false;
 			}else if(view.D_COMCD.text.length != 0 && view.D_COMCD.text.length < 10){
 				PsHrAlert.showMessage("사업자 번호가 올바르지 않습니다.");
 				return false;
 			}
//shgoo 2010.02.10 조건 추가			
			//사업자 등록번호와  주민등록번호  둘다 입력되지 않았을때
			else if((view.D_YEASUB.selectedItem.CODE != "0002" && view.D_COMCD.text.length == 0) && StringUtil.NVL(view.D_REGNO.selectedItem.CODE) == "" ) {
 				PsHrAlert.showMessage("사업자 번호, 주민등록번호 둘중에 하나는 반드시 입력해야 합니다.");
 				return false;
			}
			*/
			return true;
		} 	
			
 		//기부금 입력내역 아이템  추가
 		private function onAddItem(event:Event):void{
 			/*
 			bAdd = true;
 //shgoo 2010.02.10 조건 추가			
 			if(view.D_YEASUB.selectedItem.CODE != "0002")
 				//사업자 번호 유효성 체크 조회
 				loadBizNumValid();
 			else
				addItem();		//추가
			*/
 		}
 		
 		//기부금 입력내역 아이템  추가
 		private function addItem():void {
//shgoo : 2009.06.01 	
			//입력항목  유효성  체크		
 			if(!isInputValid())	return;
////////////// 			
			/*
 			var obj:Object = new Object();
			obj.CHECK = "NULL";
 			obj.YEASUB = view.D_YEASUB.selectedItem.CODE;
 			obj.YEASTX = view.D_YEASUB.selectedItem.TEXT;
 			obj.COMNM = view.D_COMNM.text;
 			obj.COMCD = view.D_COMCD.text;
 			obj.ENAME = view.D_REGNO.selectedItem.ENAME;
 			obj.REGNO = view.D_REGNO.selectedItem.CODE;
 			obj.RENUM = view.D_RENUM.text;
 			obj.NATCT = view.D_NATCT.value;
 			obj.NATAM = view.D_NATAM.dataValue;
 			obj.NATAM_F = view.D_NATAM.text;
 			obj.OTHCT = view.D_OTHCT.value;
 			obj.OTHAM = view.D_OTHAM.dataValue;
 			obj.OTHAM_F = view.D_OTHAM.text;
 			view.DonationData.addItem(obj);
 			//amountSum(view.D_YEASUB.selectedItem.CODE, Number(view.D_NATAM.dataValue) + Number(view.D_OTHAM.dataValue));
 			view.mainDg.selectedIndex = -1;
 			cleanData();
 			*/
 			
 		}
 		
 		//저장 벨리데이션 체크 ( 주민번호 )
 		private function isValidation(val:String):Boolean{
 			var asum:int = 0;
		    var jArr:Array = new Array(2,3,4,5,6,7,8,9,2,3,4,5);
		    var bArr:Array = new Array(10,30,70,10,30,70,10,30,5,10);
		 	var pnum:String = val;
		 	if (pnum.length == 13) {
				for (var i:int=0; i< jArr.length; i++) {
		        	asum += parseInt(pnum.substr(i, 1)) * jArr[i];
		        }
		        var achk:String  = pnum.substr(12,1);
		        var bchk:int  = (11-(asum%11))%10;
		        if (parseInt(achk) == bchk) {
		        	return true;
		        }
 				return false;
		    }
		    return false;
 		}
 		
 		
 		//기부금 입력내역 아이템  수정
 		private function onModifyItem(event:DonationItemEvent):void{
  			bAdd = false;
  			
  			itemIdx = event.itemIdx;
  			/*
 //shgoo 2010.02.10 조건 추가			
 			if(view.D_YEASUB.selectedItem.CODE != "0002")
	 			//사업자 번호 유효성 체크 조회
 				loadBizNumValid();
 			else 
				modifyItem();//수정
			*/
 		}
 		
 		//기부금 입력내역 아이템  수정
 		private function modifyItem():void {
//shgoo : 2009.06.01 	
			//입력항목  유효성  체크		
 			if(!isInputValid())	return;
////////////// 			
 			var obj:Object = new Object();
 			/*
 			obj = view.DonationData[itemIdx];
 			obj.YEASUB = view.D_YEASUB.selectedItem.CODE;
 			obj.YEASTX = view.D_YEASUB.selectedItem.TEXT;
 			obj.COMNM = view.D_COMNM.text;
 			obj.COMCD = view.D_COMCD.text;
 			obj.ENAME = view.D_REGNO.selectedItem.ENAME;
 			obj.REGNO = view.D_REGNO.selectedItem.CODE;
 			obj.RENUM = view.D_RENUM.text;
 			obj.NATCT = view.D_NATCT.value;
 			obj.NATAM = view.D_NATAM.dataValue;
 			obj.NATAM_F = view.D_NATAM.text;
 			obj.OTHCT = view.D_OTHCT.value;
 			obj.OTHAM = view.D_OTHAM.dataValue;
 			obj.OTHAM_F = view.D_OTHAM.text;
 			*/
 			view.DonationData.setItemAt(obj, itemIdx);
 			
 			/* amountMin(event.oldCode, Number(event.oldAmt1) + Number(event.oldAmt2));
 			amountSum(view.D_YEASUB.selectedItem.CODE, Number(view.D_NATAM.dataValue) + Number(view.D_OTHAM.dataValue)); */
 			
 		}
 		
 		//금액 계산
 		private function amountSum(code:String, val:Number):void{
 			/*0001: 법정기부금
 			  0002: 정치자금기부금
 			  0003: 100%한도 적용
 			  0004: 50%한도 적용 기부금
 			  0005: 종교단체 외 지정 기부금
 			  0006: 종교단체 지정 기부금
 			 */ 
 			if(code == "0001"){
 				view._donationVo.FLG01 += val;
 			}else if(code == "0002"){
 				view._donationVo.POLDN += val;
 			}else if(code == "0003"){
 				view._donationVo.FLG02 += val;
 			}else if(code == "0004"){
 				view._donationVo.SPCDO += val;
 			}else if(code == "0005"){
 				view._donationVo.DESDO += val;
 			}else if(code == "0006"){
 				view._donationVo.RELDO += val;
 			}
 		}
 		//금액 계산
 		private function amountMin(code:String, val:Number):void{
 			/*0001: 법정기부금
 			  0002: 정치자금기부금
 			  0003: 100%한도 적용
 			  0004: 50%한도 적용 기부금
 			  0005: 종교단체 외 지정 기부금
 			  0006: 종교단체 지정 기부금
 			 */ 
 			if(code == "0001"){
 				view._donationVo.FLG01 -= val;
 			}else if(code == "0002"){
 				view._donationVo.POLDN -= val;
 			}else if(code == "0003"){
 				view._donationVo.FLG02 -= val;
 			}else if(code == "0004"){
 				view._donationVo.SPCDO -= val;
 			}else if(code == "0005"){
 				view._donationVo.DESDO -= val;
 			}else if(code == "0006"){
 				view._donationVo.RELDO -= val;
 			}
 		}
 		
 		//기부금 입력내역 아이템 삭제
 		private function onDelItem(event:DonationItemEvent):void{
 			var tmp_length:int = view.DonationData.length;
        	var j:int=0;
        	for(var i:int = 0; i <= tmp_length - 1; i++){
        		if(view.DonationData[i-j].CHECK == "X"){
        			//amountMin(view.DonationData[i-j].YEASUB, Number(view.DonationData[i-j].NATAM) + Number(view.DonationData[i-j].OTHAM));
        			view.DonationData.removeItemAt(i-j);
        			j++;
        		}
        	}
 		}
 		
 		private function cleanData():void{
 			/*
 			view.D_YEASUB.selectedIndex = 0;
 			view.D_COMNM.text =  "";
 			view.D_COMCD.text =  "";
 			view.D_REGNO.selectedIndex = 0;
 			view.D_RENUM.text =  "";
 			view.D_NATCT.value =  0;
 			view.D_NATAM.dataValue =  "0";
 			view.D_OTHCT.value =  0;
 			view.D_OTHAM.dataValue =  "";
 			*/
 		}
 		
 		

		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array
		{
			return [
					YearAdjustmentFacade.LOAD_COMBO_GUBUN_COMPLETE,
					YearAdjustmentFacade.LOAD_COMBO_GUBUN_FAILED,
					YearAdjustmentFacade.LOAD_DONATION_LIST_COMPLETE,
					YearAdjustmentFacade.LOAD_DONATION_LIST_FAILED,
					YearAdjustmentFacade.SAVE_DONATION_LIST_COMPLETE,
					YearAdjustmentFacade.SAVE_DONATION_LIST_FAILED,
					YearAdjustmentFacade.LOAD_COMBO_DONAINHAB_COMPLETE,
					YearAdjustmentFacade.LOAD_COMBO_DONAINHAB_FAILED,
					YearAdjustmentFacade.LOAD_BIZ_NUM_VALID_COMPLETE,
					YearAdjustmentFacade.LOAD_BIZ_NUM_VALID_FAILED
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName()) 
			{
				case YearAdjustmentFacade.LOAD_COMBO_GUBUN_COMPLETE:
					donationListSelect();
					view.comboGubun = (note.getBody() as DonationProxy).comboGubun;
					break;
				case YearAdjustmentFacade.LOAD_COMBO_GUBUN_FAILED:
					trace("YearAdjustmentFacade.LOAD_COMBO_GUBUN_FAILED:");
					break;
				case YearAdjustmentFacade.LOAD_DONATION_LIST_COMPLETE:
					trace("YearAdjustmentFacade.LOAD_DONATION_LIST_COMPLETE:");
					view.DonationData = (note.getBody() as DonationProxy).DonationData;
					break;
				case YearAdjustmentFacade.LOAD_DONATION_LIST_FAILED:
					trace("YearAdjustmentFacade.LOAD_DONATION_LIST_FAILED:");
					break;	
				case YearAdjustmentFacade.SAVE_DONATION_LIST_COMPLETE:
					onCancelInput(null);
					//regMediator();
					facade.sendNotification(YearAdjustmentFacade.RELOAD_BASIC_DATA);
					//facade.sendNotification(YearAdjustmentView.CHECK_REQ_DONATIONSUBTRACTION);
					trace("YearAdjustmentFacade.SAVE_DONATION_LIST_COMPLETE:");
					break;
				case YearAdjustmentFacade.SAVE_DONATION_LIST_FAILED:
					PsHrAlert.showMessage((note.getBody() as DonationProxy).msgStr);
					trace("YearAdjustmentFacade.SAVE_DONATION_LIST_FAILED:");
					break;	
				case YearAdjustmentFacade.LOAD_COMBO_DONAINHAB_COMPLETE:
//shgoo 2010.01.11				
					view.comboInhabitants = (note.getBody() as DonaInhabiComboProxy).comboInhabitants;
					//view.comboInhabitants = getValidInhabitants((note.getBody() as DonaInhabiComboProxy).comboInhabitants);

					trace("YearAdjustmentFacade.LOAD_COMBO_DONAINHAB_COMPLETE:");
					break;
				case YearAdjustmentFacade.LOAD_COMBO_DONAINHAB_FAILED:
					trace("YearAdjustmentFacade.LOAD_COMBO_DONAINHAB_FAILED");
					break;	
//shgoo 2010.01.11					
				case YearAdjustmentFacade.LOAD_BIZ_NUM_VALID_COMPLETE:	//사업자 등록 번호 유효성 체크 성공
					if(bAdd) addItem();		//추가
					else modifyItem();	//수정
					break;
				case YearAdjustmentFacade.LOAD_BIZ_NUM_VALID_FAILED:	//사업자 등록 번호 유효성 체크 에러
					PsHrAlert.showMessage((note.getBody() as BizNumValidProxy).msgStr);
					break;
///////////////////////			

				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}

//shgoo 2010.01.07		
		//대상자 주민번호 추출
		private function getValidInhabitants(arrSrc:ArrayCollection):ArrayCollection {
			var arrDest:ArrayCollection = new ArrayCollection();
			
			//주민등록번호 선택 텍 스트 			
			arrDest.addItem(arrSrc.getItemAt(0));
			
			for each ( var rec:Object in arrSrc) {
				if(rec.DPTID == "X") {
					arrDest.addItem(rec);
				}
			}
			
			return arrDest;
		}
///////////////////
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():popDonation
        {
            return viewComponent as popDonation;
        }
	}
}